package fun.ticsmyc.math;

import org.junit.Test;

/**
 * @author Ticsmyc
 * @date 2020-12-06 15:02
 */
public class 平方根 {

    //二分法
    public int sqrt1(int n){
        if(n==0 || n==1) return n;
        int left =0;
        int right =n+1;
        while(left <right ){
            int mid= left+ (right-left)/2;
            if (n/mid >=mid){
                left =mid+1;
            }else{
                right =mid;
            }
        }
        return left-1;
    }

    //牛顿迭代法
    public int sqrt2(int n){
        long res =n;
        while( res*res >n){
            res = (res + n/res) /2;
        }
        return (int) res;
    }

    @Test
    public void test(){
        for(int i=0;i<100;++i){
            if(sqrt1(i) != sqrt2(i)){
                System.out.println("error" +" "+i);
                System.out.println(sqrt1(i));
                System.out.println(sqrt2(i));
                break;
            }
            System.out.println(i);
        }
    }
}
